﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Text;
using System.Security.Cryptography;
using System.IO;
public class TableSearch
{
    private string OrderDown = "/Images/TableSearch_OrderDown.png";//排序向下箭头 路径
    private string OrderUp = "/Images/TableSearch_OrderUp.png";//排序向上箭头 路径
    private string GetTableAjax = "/adming/webajax/TableSearch/GetTable.ashx";//获取列表处理页 路径
    private string UpdateTableAjax = "/adming/webajax/TableSearch/SetTable.ashx";//获取列表处理页 路径
    private string ExportAjax = "/adming/webajax/TableSearch/Export.ashx";//导出处理页 路径

    public TableSearch()
    {
    }
    public TableSearch(string ConfigUrl)
    {
        this.ConfigUrl = ConfigUrl;
        LoadXml();
    }//配置xml信息
    public TableSearch(string ConfigUrl,int flag)
    {
        this.ConfigUrl =DeCode(ConfigUrl);
        LoadXml();
    }//接收xml路径信息并解密
    private string ConfigUrl;//xml地址
    private string EnConfigUrl;//加密后的xml地址
    public string where = "";//可写查询语句
    private string Enwhere;//加密后的可写查询语句
    public string field = "";//公共返回字段
    private string Lock;//区分锁
    private string Custom;//自定义处理页 JS调用方法Custom+Lock+()
    private string Function = "";//自定义方法 GetTable() 方法中最后执行
    private bool IsSearch = true;

    private string Name;//表名
    private string PK;//主键或唯一字段
    private string Field;//返回字段
    private string Order;//默认排序
    private string Where;//必然查询语句
    private int PageSize;//页尺寸
    private int Span;//分页跨度
    private int p = 1;//当前页
    private XmlDocument Table = new XmlDocument();//xml对象
    private XmlNode TableNode;//xml对象
    private XmlNodeList TableList;//xml对象

    Regex reg = new Regex("{[^{^}]+}");//绑定用正则表达式
    private DataTable dtlist;//查询出来的DataTable
    private int dti;//DataTable 循环字段
    private NameValueCollection NameValue;//接收的Ajax参数
    private byte[] Keys = { 0x32, 0x35, 0x83, 0x72, 0x19, 0xFF, 0xBA, 0xAF };//默认密钥向量   
    private string Key = "zseqwed3";//密钥

    // 加载表头 查询行 初始列表 JS 
    public string LoadTable()
    {
        Enwhere = EnCode(where);
        StringBuilder str = new StringBuilder();
        str.Append("<table class='TableSearch' cellpadding='0' cellspacing='0'>");
        str.Append(GetTitle());
        str.Append(GetSearch());
        str.AppendFormat("<tbody id='TList{0}'>{1}</tbody>", Lock, GetList());
        str.Append("</table>");
        str.Append(GetPage());
        str.Append(GetJS());
        str.Append(GetAjax());
        
        return str.ToString();
    }
    //初始化 读取xml 基础配置
    private void LoadXml()
    {
        Table.Load(HttpContext.Current.Request.MapPath("~") + ConfigUrl);
        EnConfigUrl = EnCode(ConfigUrl);
        TableNode = Table.SelectSingleNode("Table").SelectSingleNode("TableSearch");
        TableList = TableNode.ChildNodes;
        Name = TableNode.Attributes["Name"].Value;
        PK = TableNode.Attributes["PK"].Value;
        Field = TableNode.Attributes["Field"] == null ? "*" : TableNode.Attributes["Field"].Value;
        Order = TableNode.Attributes["Order"] == null ? "" : TableNode.Attributes["Order"].Value;
        Where = TableNode.Attributes["Where"] == null ? "" : TableNode.Attributes["Where"].Value;
        PageSize = TableNode.Attributes["PageSize"] == null ? 15 : int.Parse(TableNode.Attributes["PageSize"].Value);
        Span = TableNode.Attributes["Span"] == null ? 5 : int.Parse(TableNode.Attributes["Span"].Value);
        Lock = TableNode.Attributes["Lock"] == null ? "" : TableNode.Attributes["Lock"].Value;
        Custom = TableNode.Attributes["Custom"] == null ? "" : TableNode.Attributes["Custom"].Value;
        Function = TableNode.Attributes["Function"] == null ? "" : TableNode.Attributes["Function"].Value;
        IsSearch = TableNode.Attributes["IsSearch"] == null ? true : bool.Parse(TableNode.Attributes["IsSearch"].Value);
        for (int i = 0; i < TableList.Count; i++)
        {
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            if (SearchType.IndexOf("Select") != -1)
            {
                if (TableList.Item(i).Attributes["SQL"] != null)
                {
                    DataTable dt = DBHelper.GetDataTable(TableList.Item(i).Attributes["SQL"].Value);
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        XmlElement xe = Table.CreateElement("option");
                        xe.InnerText = dt.Rows[j]["Name"].ToString();
                        xe.SetAttribute("value", dt.Rows[j]["Value"].ToString());
                        TableList.Item(i).AppendChild(xe);
                    }
                }
            }
        }
    }
    //初始化获取表Title
    private string GetTitle()
    {
        StringBuilder Title = new StringBuilder();
        Title.Append("<tbody id='Title'><tr class='tr TTitle'>");
        for (int i = 0; i < TableList.Count; i++)
        {
            if (TableList.Item(i).Attributes["IsOrder"] != null && TableList.Item(i).Attributes["IsOrder"].Value == "True")
                Title.Append("<td class='td TTitle" + i + "'><a class='TOrder' onclick=\"GetOrder" + Lock + "('TO_" + i + "" + Lock + "',this);\">" + TableList.Item(i).Attributes["Title"].Value + " </a> <img src='/Images/TableSearch_OrderDown.png' id='TO_" + i + "" + Lock + "' style='display:none'/></td>");
            else if (TableList.Item(i).Attributes["SearchType"].Value=="Hide") { }
            else
                Title.AppendFormat("<td class='td TTitle{0}'>{1}</td>", i, TableList.Item(i).Attributes["Title"].Value);
        }
        Title.Append("</tr></tbody>");
        return Title.ToString();
    }
    //初始化获取查询行
    private string GetSearch()
    {
        StringBuilder Search = new StringBuilder();
        Search.Append("<tbody id='TSearch" + Lock + "' " + (IsSearch ? "" : "style='display:none'") + "><tr class='tr TSearch'>");
        for (int i = 0; i < TableList.Count; i++)
        {
            string Bind = TableList.Item(i).Attributes["Bind"] == null ? "" : TableList.Item(i).Attributes["Bind"].Value;
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            if (SearchType == "Between")
            {
                Search.Append("<td class='td TSearch" + i + "'>"
                       + "<input type='text' name='TS_" + i + "_left" + Lock + "' class='TS_Between' onkeyup='GetTable" + Lock + "(1)' autocomplete='off'/>"
                       + "-<input type='text' name='TS_" + i + "_right" + Lock + "' class='TS_Between' onkeyup='GetTable" + Lock + "(1)' autocomplete='off'/></td>");
            }
            else if (SearchType.IndexOf("Time") != -1)
            {
                Search.Append("<td class='td TSearch" + i + "'>"
                       + "<input type='text' name='TS_" + i + "_left" + Lock + "' class='TS_Time' onfocus='WdatePicker();GetTable" + Lock + "(1);'/>"
                       + "-<input type='text' name='TS_" + i + "_right" + Lock + "' class='TS_Time' onfocus='WdatePicker();GetTable" + Lock + "(1);'/></td>");
            }
            else if (SearchType.IndexOf("Select") != -1)
            {
                XmlNodeList xnl = TableList.Item(i).ChildNodes;
                Search.Append("<td class='td TSearch" + i + "'>"
                       + "<select name='TS_" + i + "" + Lock + "' class='TS_Select' onchange='GetTable" + Lock + "(1);' autocomplete='off'>");
                Search.Append("<option value=''>请选择</option>");


                for (int j = 0; j < xnl.Count; j++)
                {
                    Search.Append("<option value='" + xnl.Item(j).Attributes["value"].Value + "'>" + xnl.Item(j).InnerText + "</option>");
                }
                Search.Append("</select></td>");
            }
            else if (SearchType == "Empty")
            {
                Search.Append("<td class='td TSearch" + i + " Empty' ><a onclick='Empty" + Lock + "()'>Clear</a></td>");
            }
            else if (SearchType == "EmptyExport")
            {
                Search.Append("<td class='td TSearch" + i + " Empty' ><a onclick='Empty" + Lock + "()'>Clear</a> <a onclick='Export" + Lock + "()'>导出</a></td>");
            }
            else if (SearchType == "Export")
            {
                Search.Append("<td class='td TSearch" + i + "' class='Empty'><a onclick='Export" + Lock + "()'>导出</a></td>");
            }
            else if (SearchType.IndexOf("None") != -1)
            {
                Search.Append("<td class='td TSearch" + i + "'><div class='TS_None'></div></td>");
            }
            else if (SearchType == "SelAll")
            {
                Search.Append("<td class='td TSearch" + i + "'><input type='checkbox' onclick='SelAll(this)'/></td>");
            }
            else if (SearchType == "Hide")
            {
            }
            else
            {
                Search.Append("<td class='td TSearch" + i + "'><input type='text' name='TS_" + i + "" + Lock + "' class='TS_Text' onkeyup='GetTable" + Lock + "(1);' /></td>");
            }
        }
        Search.Append("</tr></tbody>");
        return Search.ToString();
    }
    //初始化列表
    private string GetList()
    {
        if (where != "")
            Where += (Where == "" ? "" : " and ") + where;
        //dtlist = DBHelper.GetDataTable("exec Table_Pagination '" + Name + "','" + PK + "','" + Field.Replace("'", "''") + (field != "" ? "," + field.Replace("'", "''") : "") + "','" + (Order == "" ? "" : "Order by " + Order) + "'," + PageSize + "," + p + ",'" + Where.Replace("'", "''") + "'");
        dtlist = Pagination.GetPagination(Name, Field.Replace("'", "''") + (field != "" ? "," + field.Replace("'", "''") : ""), Order, PK, PageSize, p, Where);
        StringBuilder List = new StringBuilder();
        for (dti = 0; dti < dtlist.Rows.Count; dti++)
        {
            List.AppendFormat("<tr class='tr TList{0}'>", dti);
            for (int j = 0; j < TableList.Count; j++)
            {
                string Bind = TableList.Item(j).Attributes["Bind"] == null ? "" : TableList.Item(j).Attributes["Bind"].Value;
                string BindType = TableList.Item(j).Attributes["BindType"] == null ? "" : TableList.Item(j).Attributes["BindType"].Value;
                string SearchType = TableList.Item(j).Attributes["SearchType"] == null ? "Equals" : TableList.Item(j).Attributes["SearchType"].Value;
                if (BindType == "Time")
                {
                    List.AppendFormat("<td class='td TList{0}'>&nbsp;{1}</td>", j, (dtlist.Rows[dti][Bind] == null || dtlist.Rows[dti][Bind].ToString() == "" ? "" : Convert.ToDateTime(dtlist.Rows[dti][Bind]).ToString(TableList.Item(j).InnerText)));
                }
                else if (BindType == "Html")
                {
                    List.AppendFormat("<td class='td TList{0}'>{1}</td>", j, reg.Replace(TableList.Item(j).InnerXml, new MatchEvaluator(GetBind)));
                }
                else if (BindType == "Select")
                {
                    XmlNodeList xnl = TableList.Item(j).ChildNodes;
                    List.AppendFormat("<td class='td TList{0}'>&nbsp;", j);
                    int f = 0;
                    for (int k = 0; k < xnl.Count; k++)
                    {
                        if (xnl.Item(k).Attributes["value"].Value == dtlist.Rows[dti][Bind].ToString())
                        {
                            List.Append(reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind)));
                            f = 1;
                            break;
                        }
                        else if (xnl.Item(k).Attributes["session"] != null)
                        {
                            System.Web.UI.Page page = new System.Web.UI.Page();
                            if (page.Session[xnl.Item(k).Attributes["session"].Value].ToString() == dtlist.Rows[dti][Bind].ToString())
                            {
                                List.Append(reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind)));
                                f = 1;
                                break;
                            }
                        }
                        else if (xnl.Item(k).Attributes["else"] != null)
                        {
                            List.Append(reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind)));
                            f = 1;
                            break;
                        }
                    }
                    if (f == 0)
                        List.Append(dtlist.Rows[dti][Bind].ToString());
                    List.AppendFormat("</td>");
                }
                else if (BindType == "Hide")
                {
                }
                else
                {
                    if (TableList.Item(j).Attributes["Fuzzy"] != null && TableList.Item(j).Attributes["Fuzzy"].Value == "True")
                    {
                        Regex reg = new Regex(".");
                        string value = dtlist.Rows[dti][Bind].ToString();
                        if (value.Length > 7) {
                            value = reg.Replace(value, "*", value.Length - 6, 3);
                        }
                        List.AppendFormat("<td class='td TList{0}'>&nbsp;{1}</td>", j, value);
                    }
                    else
                        List.AppendFormat("<td class='td TList{0}'>&nbsp;{1}</td>", j, dtlist.Rows[dti][Bind]);
                }
            }
            List.Append("</tr>");
        }
        return List.ToString();
    }
    //获取分页
    public string GetPage()
    {
        string Page = "";
        //DataTable dtcount = DBHelper.GetDataTable("exec Table_Count '" + Name + "','" + Where.Replace("'", "''") + "'");
        int dtcount = Pagination.GetCount(Name, Where);
        int PageCount = Convert.ToInt32(Math.Ceiling(dtcount / (double)PageSize));
        PageCount = PageCount == 0 ? 1 : PageCount;
        if (PageCount == 1) return Page;
        Page += "<input type='hidden' value='" + p + "' id='TS_p'/><a class='fy_o fa fa-angle-double-left' onclick='GetTable" + Lock + "(1)'></a>";
        Page += " <a class='fy_o fa fa-angle-left' onclick='GetTable" + Lock + "(" + (p - 1 >= 1 ? p - 1 : 1) + ")'></a>";
        int f = (Span - 1) / 2;
        int i_b = (p - f <= 1 || PageCount - Span <= 0) ? 1 : (PageCount - p > f ? p - f : PageCount - (Span - 1));
        for (int i = i_b; i <= i_b + (Span - 1) && i <= PageCount; i++)
        {
            Page += " <a " + (i == p ? "class='fy_on'" : "class='fy_a' onclick='GetTable" + Lock + "(" + i + ")'") + " >" + i + "</a>";
        }
        Page += " <a onclick='GetTable" + Lock + "(" + (p + 1 <= PageCount ? p + 1 : PageCount) + ")' class='fy_o fa fa-angle-right'></a>";
        Page += " <a class='fy_o fa fa-angle-double-right' onclick='GetTable" + Lock + "(" + PageCount + ")'></a> <span>共 " + PageCount + " 页</span>";
        Page += " &nbsp;<input type='text' id='" + Name + "page'  onkeyup=\"if(event.keyCode!=37 && event.keyCode!=39) value=value.replace(/\\D/g, '');\" onbeforepaste= \"clipboardData.setData('text',clipboardData.getData('text').replace(/\\D/g,''))\"/> <a onclick=\"GetTable" + Lock + "($('#" + Name + "page').val()==''?1:$('#" + Name + "page').val())\" class='fy_go'>go</a>";
        return "<div class='Fy' id='TFy" + Lock + "' >" + Page + "</div>";
    }
    //初始化JS
    private string GetJS()
    {
        string Fjs = "";
        string JS = "<script type='text/javascript'>";
        JS += "function GetTable" + Lock + "(p,callback)";
        JS += "{";
        string JSx = "";
        for (int i = 0; i < TableList.Count; i++)
        {
            string Bind = TableList.Item(i).Attributes["Bind"] == null ? "" : TableList.Item(i).Attributes["Bind"].Value;
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            string IsOrder = TableList.Item(i).Attributes["IsOrder"] == null ? "False" : TableList.Item(i).Attributes["IsOrder"].Value;
            if (Bind != "")
            {
                if (SearchType.IndexOf("Time") != -1 || SearchType == "Between")
                {
                    JSx += "var TS_" + i + "_left = " + "$(\"[name='TS_" + i + "_left" + Lock + "']\").val();";
                    JSx += "var TS_" + i + "_right = " + "$(\"[name='TS_" + i + "_right" + Lock + "']\").val();";
                    Fjs += " ,TS_" + i + "_left:TS_" + i + "_left";
                    Fjs += " ,TS_" + i + "_right:TS_" + i + "_right";
                }
                else
                {
                    JSx += "var TS_" + i + " = " + "$(\"[name='TS_" + i + "" + Lock + "']\").val();";
                    Fjs += " ,TS_" + i + ":TS_" + i;
                }
            }
            if (IsOrder == "True")
            {
                JSx += "var TO_" + i + " = " + "$(\"#TO_" + i + "" + Lock + "\").css('display')=='none'?'':$(\"#TO_" + i + "" + Lock + "\").attr('src');";
                Fjs += " ,TO_" + i + ":TO_" + i;
            }
        }
        //获取列表
        JS += JSx;
        JS += " $.get(\""+GetTableAjax+"\", { ConfigUrl:'" + EnConfigUrl + "',p:p" + Fjs + ",TSwhere:'" + Enwhere
 + "',TSfield:'" + field + "', time: new Date().getTime() }, function (html) { ";
        JS += "$('#TList" + Lock + "').html(html.split(\"<[zyr]>\")[0]);";
        JS += "$('#TFy" + Lock + "').html(html.split(\"<[zyr]>\")[1]);";
        JS += Function;
        JS += "if(callback) callback();";
        JS += "});";
        JS += "}";
        if (Custom != "")
        {
            JS += "function CustomJs" + Lock + "(){";
            JS += JSx;
            JS += " $.get(\"" + Custom + "\", { ConfigUrl:'" + EnConfigUrl + "',p:p" + Fjs + ",TSwhere:'" + Enwhere
    + "',TSfield:'" + field + "', time: new Date().getTime() }, function (html) { ";
            JS += "$('#TList" + Lock + "').html(html.split(\"<[zyr]>\")[0]);";
            JS += "$('#TFy" + Lock + "').html(html.split(\"<[zyr]>\")[1]);";
            JS += "});";
            JS += "}";
        }
        string Ejs = "";
        //导出
        JS += "function Export" + Lock + "()";
        JS += "{";
        for (int i = 0; i < TableList.Count; i++)
        {
            string Bind = TableList.Item(i).Attributes["Bind"] == null ? "" : TableList.Item(i).Attributes["Bind"].Value;
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            string IsOrder = TableList.Item(i).Attributes["IsOrder"] == null ? "False" : TableList.Item(i).Attributes["IsOrder"].Value;
            if (Bind != "")
            {
                if (SearchType.IndexOf("Time") != -1 || SearchType == "Between")
                {
                    JS += "var TS_" + i + "_left = " + "$(\"[name='TS_" + i + "_left']\").val();";
                    JS += "var TS_" + i + "_right = " + "$(\"[name='TS_" + i + "_right']\").val();";
                    Ejs += "&TS_" + i + "_left='+encodeURI(TS_" + i + "_left)+'";
                    Ejs += "&TS_" + i + "_right='+encodeURI(TS_" + i + "_right)+'";
                }
                else
                {
                    JS += "var TS_" + i + " = " + "$(\"[name='TS_" + i + "']\").val();";
                    Ejs += "&TS_" + i + "='+encodeURI(TS_" + i + ")+'";
                }
            }
            if (IsOrder == "True")
            {
                JS += "var TO_" + i + " = " + "$(\"#TO_" + i + "\").css('display')=='none'?'':$(\"#TO_" + i + "\").attr('src');";
                Ejs += "&TO_" + i + "='+TO_" + i + "+'";
            }
        }
        JS += "window.open('" + ExportAjax + "?ConfigUrl=" + Uri.EscapeDataString(EnConfigUrl) + "" + Ejs + "&TSwhere=" + Uri.EscapeDataString(Enwhere) + "&TSfield=" + field + "')";
        JS += "}";


        JS += "function Empty" + Lock + "()";
        JS += "{";
        for (int i = 0; i < TableList.Count; i++)
        {
            string Bind = TableList.Item(i).Attributes["Bind"] == null ? "" : TableList.Item(i).Attributes["Bind"].Value;
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            string IsOrder = TableList.Item(i).Attributes["IsOrder"] == null ? "False" : TableList.Item(i).Attributes["IsOrder"].Value;
            if (Bind != "")
            {
                if (SearchType.IndexOf("Time") != -1 || SearchType == "Between")
                {
                    JS += "$(\"[name='TS_" + i + "_left" + Lock + "']\").val('');";
                    JS += "$(\"[name='TS_" + i + "_right" + Lock + "']\").val('');";
                }
                else
                {
                    JS += "$(\"[name='TS_" + i + "" + Lock + "']\").val('');";
                }
            }
            if (IsOrder == "True")
            {
                JS += "$(\"#TO_" + i + "" + Lock + "\").css('display','none');";
            }
        }
        JS += "GetTable" + Lock + "(1)";
        JS += "}";
        JS += "function GetOrder" + Lock + "(ID,Obj)";
        JS += "{";
        JS += "if($('#'+ID).css('display')=='none')";
        JS += "{$('#'+ID).css('display','');}";
        JS += "else";
        JS += "{";
        JS += "if($('#'+ID).attr('src')=='" + OrderDown + "')";
        JS += "{$('#'+ID).attr('src','" + OrderUp + "');}";
        JS += "else";
        JS += "{$('#'+ID).attr('src','" + OrderDown + "');}";
        JS += "}GetTable" + Lock + "(1);";
        JS += "}";
        //
        JS += "function SelAll(obj)";
        JS += "{";
        JS += "if($(obj).attr('checked'))";
        JS += "{$('#TList" + Lock + "').find(\"[type='checkbox']\").attr('checked',true);}";
        JS += "else";
        JS += "{$('#TList" + Lock + "').find(\"[type='checkbox']\").attr('checked',false);}";
        JS += "}";

        JS += "</script>";
        return JS;
    }
    //注册Ajax方法
    private string GetAjax()
    {
        if (Table.SelectSingleNode("Table").SelectSingleNode("Ajax") != null)
        {
            string[] strlist;
            string str = "";
            string Ajax = "<script type='text/javascript'>";

            XmlNodeList AjaxList = Table.SelectSingleNode("Table").SelectSingleNode("Ajax").ChildNodes;
            for (int i = 0; i < AjaxList.Count; i++)
            {
                str = "";
                strlist = AjaxList[i].Attributes["Parameter"].Value.Split(',');
                Ajax += "function " + AjaxList[i].Attributes["Name"].Value + "(" + AjaxList[i].Attributes["Parameter"].Value + "){";
                for (int j = 0; j < strlist.Length; j++)
                {
                    str += "," + strlist[j] + ":" + strlist[j];
                }
                if (AjaxList[i].Attributes["SQL"] != null && AjaxList[i].Attributes["SQL"].Value != "")
                {
                    Ajax += " $.get(\""+UpdateTableAjax+"\", { ConfigUrl:'" + EnConfigUrl + "',FunctionName:'" + AjaxList[i].Attributes["Name"].Value + "'," + str.Remove(0, 1) + ", time: new Date().getTime() }, function (" + (AjaxList[i].Attributes["Return"] != null ? AjaxList[i].Attributes["Return"].Value : "data") + ") { ";
                    Ajax += AjaxList[i].InnerXml;
                    if (AjaxList[i].Attributes["IsUpdate"] != null)
                        Ajax += "GetTable" + Lock + "($('#TS_p').val());";
                    Ajax += "});";
                }
                else
                    Ajax += AjaxList[i].InnerXml;

                Ajax += "}";
            }
            return Ajax += "</script>";
        }
        else
            return "";
    }
    //用正则表达式进行列表绑定
    private string GetBind(Match m)
    {
        if (m.Value.IndexOf("Session") < 0)
        {
            string str = m.Value.Replace("{", "").Replace("}", "");
            return dtlist.Rows[dti][str].ToString();
        }
        else
        {
            string str = m.Value.Replace("{Session[", "").Replace("]}", "");
            System.Web.UI.Page page = new System.Web.UI.Page();
            return page.Session[str].ToString();
        }
    }
    //获取列表
    public string GetTable(NameValueCollection nvc)
    {

        //获取用户设置的where
        where = DeCode(nvc["TSwhere"]);
        field = nvc["TSfield"];
        if (where != "")
            Where += (Where == "" ? "" : " and ") + where;
        //获取页数
        p = int.Parse(nvc["p"].ToString());

        string FWhere = "";
        string FOrder = "";
        for (int i = 0; i < TableList.Count; i++)
        {
            //生成Where
            string Bind = TableList.Item(i).Attributes["Bind"] == null ? "" : TableList.Item(i).Attributes["Bind"].Value;
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            if (Bind == "")
                continue;
            if (SearchType == "Between")
            {
                if (nvc["TS_" + i + "_left"] != "")
                    FWhere += Bind + ">=" + nvc["TS_" + i + "_left"] + " and ";
                if (nvc["TS_" + i + "_right"] != "")
                    FWhere += Bind + "<=" + nvc["TS_" + i + "_right"] + " and ";

            }
            else if (SearchType == "Time")
            {
                if (nvc["TS_" + i + "_left"] != "")
                    FWhere += Bind + ">'" + nvc["TS_" + i + "_left"] + "' and ";
                if (nvc["TS_" + i + "_right"] != "")
                    FWhere += Bind + "<dateadd(day,1,'" + nvc["TS_" + i + "_right"] + "') and ";

            }
            else if (SearchType == "Like")
            {
                if (nvc["TS_" + i] != "")
                    FWhere += "[" + Bind + "] like '%" + nvc["TS_" + i] + "%' and ";
            }
            else if (SearchType == "Equals" || SearchType == "==" || SearchType == "Select")
            {
                if (nvc["TS_" + i] != "")
                    FWhere += Bind + "='" + nvc["TS_" + i] + "' and ";
            }
            else if (SearchType.IndexOf("FK") != -1)
            {
                if (nvc["TS_" + i] != "")
                {
                    string[] str = Field.Split(',');
                    for (int j = 0; j < str.Length; j++)
                    {
                        if (str[j].IndexOf(Bind) != -1)
                        {
                            string fk = str[j].Remove(0, str[j].IndexOf('=') + 1);
                            fk = fk.Remove(0, fk.IndexOf('=') + 1).Replace(")", "").Trim();
                            string pk = str[j].Remove(0, str[j].IndexOf("where") + 5);
                            pk = pk.Remove(pk.IndexOf('=')).Trim();
                            string fktable = str[j].Remove(0, str[j].IndexOf("from") + 4);
                            fktable = fktable.Remove(fktable.IndexOf("where")).Trim();
                            string searchname = str[j].Remove(0, str[j].IndexOf("select") + 6);
                            searchname = searchname.Remove(searchname.IndexOf("from")).Trim();
                            if (SearchType.IndexOf("Equals") != -1 || SearchType.IndexOf("==") != -1)
                            {
                                FWhere += fk + " in (select " + pk + " from " + fktable + " where " + searchname + " ='" + nvc["TS_" + i] + "') and ";
                            }
                            else if (SearchType.IndexOf("Like") != -1)
                            {
                                FWhere += fk + " in (select " + pk + " from " + fktable + " where " + searchname + " like '%" + nvc["TS_" + i] + "%') and ";
                            }
                            else if (SearchType.IndexOf("Select") != -1)
                            {
                                FWhere += fk + " in (select " + pk + " from " + fktable + " where " + searchname + " ='" + nvc["TS_" + i] + "') and ";
                            }
                            else if (SearchType.IndexOf("Time") != -1)
                            {
                                if (nvc["TS_" + i + "_left"] != "" || nvc["TS_" + i + "_right"] != "")
                                {
                                    FWhere += fk + " in (select " + pk + " from " + fktable + " where ";
                                    if (nvc["TS_" + i + "_left"] != "")
                                        FWhere += searchname + ">'" + nvc["TS_" + i + "_left"] + "'";
                                    if (nvc["TS_" + i + "_right"] != "")
                                        FWhere += searchname + "<'" + nvc["TS_" + i + "_right"] + "'";
                                    FWhere += ") and ";
                                }
                            }
                        }

                    }
                }
            }
            else if (SearchType == "None" || SearchType == "SelAll" || SearchType == "Empty")
            {

            }

            //生成Order
            string IsOrder = TableList.Item(i).Attributes["IsOrder"] == null ? "False" : TableList.Item(i).Attributes["IsOrder"].Value;
            if (IsOrder == "True")
            {
                if (nvc["TO_" + i] != "")
                    FOrder += "," + Bind + (nvc["TO_" + i] == "/Images/TableSearch_OrderDown.png" ? "" : " desc");
            }
        }
        if (FWhere != "" && Where != "")
            Where = FWhere + Where;
        else if (FWhere != "" && Where == "")
            Where = FWhere.Remove(FWhere.Length - 5);
        Order = FOrder != "" ? FOrder.Remove(0, 1) : Order;
        //开始查询
        //dtlist = DBHelper.GetDataTable("exec Table_Pagination '" + Name + "','" + PK + "','" + Field.Replace("'", "''") + (field != "" ? "," + field.Replace("'", "''") : "") + "','" + (Order == "" ? "" : "Order by " + Order) + "'," + PageSize + "," + p + ",'" + Where.Replace("'", "''") + "'");
        dtlist = Pagination.GetPagination(Name, Field.Replace("'", "''") + (field != "" ? "," + field.Replace("'", "''") : ""), Order, PK, PageSize, p, Where);

        string List = "";
        for (dti = 0; dti < dtlist.Rows.Count; dti++)
        {
            List += "<tr class='tr TList" + dti + "'>";
            for (int j = 0; j < TableList.Count; j++)
            {
                string Bind = TableList.Item(j).Attributes["Bind"] == null ? "" : TableList.Item(j).Attributes["Bind"].Value;
                string BindType = TableList.Item(j).Attributes["BindType"] == null ? "" : TableList.Item(j).Attributes["BindType"].Value;
                string SearchType = TableList.Item(j).Attributes["SearchType"] == null ? "Equals" : TableList.Item(j).Attributes["SearchType"].Value;
                if (BindType == "Time")
                {
                    List += "<td class='td TList" + j + "'>&nbsp;"
                         + (dtlist.Rows[dti][Bind] == null || dtlist.Rows[dti][Bind].ToString() == "" ? "" : Convert.ToDateTime(dtlist.Rows[dti][Bind]).ToString(TableList.Item(j).InnerText)) + "</td>";
                }
                else if (BindType == "Html")
                {
                    List += "<td class='td TList" + j + "'>"
                         + reg.Replace(TableList.Item(j).InnerXml, new MatchEvaluator(GetBind)) + "</td>";
                }
                else if (BindType == "Select")
                {
                    XmlNodeList xnl = TableList.Item(j).ChildNodes;
                    List += "<td class='td TList" + j + "'>&nbsp;";
                    int f = 0;
                    for (int k = 0; k < xnl.Count; k++)
                    {
                        if (xnl.Item(k).Attributes["value"].Value == dtlist.Rows[dti][Bind].ToString())
                        {
                            List += reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind));
                            f = 1;
                            break;
                        }
                        else if (xnl.Item(k).Attributes["session"] != null)
                        {
                            System.Web.UI.Page page = new System.Web.UI.Page();
                            if (page.Session[xnl.Item(k).Attributes["session"].Value].ToString() == dtlist.Rows[dti][Bind].ToString())
                            {
                                List += reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind));
                                f = 1;
                                break;
                            }
                        }
                        else if (xnl.Item(k).Attributes["else"] != null)
                        {
                            List += reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind));
                            f = 1;
                            break;
                        }
                    }
                    if (f == 0)
                        List += dtlist.Rows[dti][Bind].ToString();
                    List += "</td>";
                }
                else
                {
                    if (TableList.Item(j).Attributes["Fuzzy"] != null && TableList.Item(j).Attributes["Fuzzy"].Value == "True")
                    {
                        Regex reg = new Regex(".");
                        string value = dtlist.Rows[dti][Bind].ToString();
                        if (value.Length > 7)
                        {
                            value = reg.Replace(value, "*", value.Length - 6, 3);
                        }
                        List += "<td class='td TList" + j + "'>&nbsp;" + value + "</td>";
                    }
                    else
                        List += "<td class='td TList" + j + "'>&nbsp;" + dtlist.Rows[dti][Bind] + "</td>";
                }
            }
            List += "</tr>";
        }
        return List;
    }
    //执行Ajax方法
    public string ExecutionAjax(NameValueCollection nvc)
    {
        NameValue=nvc;
        if (Table.SelectSingleNode("Table").SelectSingleNode("Ajax") != null)
        {
            string str = "";
            XmlNodeList AjaxList = Table.SelectSingleNode("Table").SelectSingleNode("Ajax").ChildNodes;
            for (int i = 0; i < AjaxList.Count; i++)
            {
                if (AjaxList[i].Attributes["Name"].Value == nvc["FunctionName"])
                {
                    str = DBHelper.ExecuteCommand(reg.Replace(AjaxList[i].Attributes["SQL"].Value, ReturnSQL)).ToString();
                    if (AjaxList[i].Attributes["FileDel"] != null)
                    {
                        System.Web.UI.Page page = new System.Web.UI.Page();
                        File.Delete(page.Server.MapPath("~") + reg.Replace(AjaxList[i].Attributes["SQL"].Value, ReturnSQL));
                    }
                }
            }
            return str;
        }
        else
            return "";
    }
    //绑定运行SQL正则
    private string ReturnSQL(Match m)
    {
        if (m.Value.IndexOf("Session") < 0)
        {
            string str = m.Value.Replace("{", "").Replace("}", "");
            return NameValue[str];
        }
        else
        {
            string str = m.Value.Replace("{Session[", "").Replace("]}", "");
            System.Web.UI.Page page = new System.Web.UI.Page();
            return page.Session[str].ToString();
        }
    }
    //加密
    private string EnCode(string EnStr)
    {
        byte[] rgbKey = Encoding.UTF8.GetBytes(Key.Substring(0, 8));
        byte[] rgbIV = Keys;
        byte[] inputByteArray = Encoding.UTF8.GetBytes(EnStr);
        DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());
    }
    //解密
    private string DeCode(string DeStr)
    {
        try
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes(Key);
            byte[] rgbIV = Keys;
            byte[] inputByteArray = Convert.FromBase64String(DeStr);
            DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }
        catch
        {
            return DeStr;
        } 
    }
    //导出Excel
    public StringBuilder Export(NameValueCollection nvc)
    {

        //获取用户设置的where
        where = DeCode(nvc["TSwhere"]);
        if (where != "")
            Where += (Where == "" ? "" : " and ") + where;

        string FWhere = "";
        string FOrder = "";
        string NewField = "";
        for (int i = 0; i < TableList.Count; i++)
        {
            //生成Where
            string Bind = TableList.Item(i).Attributes["Bind"] == null ? "" : TableList.Item(i).Attributes["Bind"].Value;
            string SearchType = TableList.Item(i).Attributes["SearchType"] == null ? "Equals" : TableList.Item(i).Attributes["SearchType"].Value;
            if (Bind == "")
                continue;
            if (SearchType == "Between")
            {
                if (nvc["TS_" + i + "_left"] != "")
                    FWhere += Bind + ">" + nvc["TS_" + i + "_left"] + " and ";
                if (nvc["TS_" + i + "_right"] != "")
                    FWhere += Bind + "<" + nvc["TS_" + i + "_right"] + " and ";

            }
            else if (SearchType == "Time")
            {
                if (nvc["TS_" + i + "_left"] != "")
                    FWhere += Bind + ">'" + nvc["TS_" + i + "_left"] + "' and ";
                if (nvc["TS_" + i + "_right"] != "")
                    FWhere += Bind + "<'" + nvc["TS_" + i + "_right"] + "' and ";

            }
            else if (SearchType == "Like")
            {
                if (nvc["TS_" + i] != "")
                    FWhere += Bind + " like '%" + nvc["TS_" + i] + "%' and ";
            }
            else if (SearchType == "Equals" || SearchType == "==" || SearchType == "Select")
            {
                if (nvc["TS_" + i] != "")
                    FWhere += Bind + "='" + nvc["TS_" + i] + "' and ";
            }
            else if (SearchType.IndexOf("FK") != -1)
            {
                if (nvc["TS_" + i] != "")
                {
                    string[] str = Field.Split(',');
                    for (int j = 0; j < str.Length; j++)
                    {
                        if (str[j].IndexOf(Bind) != -1)
                        {
                            string fk = str[j].Remove(0, str[j].IndexOf('=') + 1);
                            fk = fk.Remove(0, fk.IndexOf('=') + 1).Replace(")", "").Trim();
                            string pk = str[j].Remove(0, str[j].IndexOf("where") + 5);
                            pk = pk.Remove(pk.IndexOf('=')).Trim();
                            string fktable = str[j].Remove(0, str[j].IndexOf("from") + 4);
                            fktable = fktable.Remove(fktable.IndexOf("where")).Trim();
                            string searchname = str[j].Remove(0, str[j].IndexOf("select") + 6);
                            searchname = searchname.Remove(searchname.IndexOf("from")).Trim();
                            if (SearchType.IndexOf("Equals") != -1 || SearchType.IndexOf("==") != -1)
                            {
                                FWhere += fk + " in (select " + pk + " from " + fktable + " where " + searchname + " ='" + nvc["TS_" + i] + "') and ";
                            }
                            else if (SearchType.IndexOf("Like") != -1)
                            {
                                FWhere += fk + " in (select " + pk + " from " + fktable + " where " + searchname + " like '%" + nvc["TS_" + i] + "%') and ";
                            }
                            else if (SearchType.IndexOf("Select") != -1)
                            {
                                FWhere += fk + " in (select " + pk + " from " + fktable + " where " + searchname + " ='" + nvc["TS_" + i] + "') and ";
                            }
                            else if (SearchType.IndexOf("Time") != -1)
                            {
                                if (nvc["TS_" + i + "_left"] != "" || nvc["TS_" + i + "_right"] != "")
                                {
                                    FWhere += fk + " in (select " + pk + " from " + fktable + " where ";
                                    if (nvc["TS_" + i + "_left"] != "")
                                        FWhere += searchname + ">'" + nvc["TS_" + i + "_left"] + "'";
                                    if (nvc["TS_" + i + "_right"] != "")
                                        FWhere += searchname + "<'" + nvc["TS_" + i + "_right"] + "'";
                                    FWhere += ") and ";
                                }
                            }
                        }

                    }
                }
            }
            else if (SearchType == "None" || SearchType == "Empty")
            {

            }

            //生成Order
            string IsOrder = TableList.Item(i).Attributes["IsOrder"] == null ? "False" : TableList.Item(i).Attributes["IsOrder"].Value;
            if (IsOrder == "True")
            {
                if (nvc["TO_" + i] != "")
                    FOrder += "," + Bind + (nvc["TO_" + i] == "/Images/TableSearch_OrderDown.png" ? "" : " desc");
            }

            if (SearchType.IndexOf("FK") != -1)
            {
                string[] str = Field.Split(',');
                for (int j = 0; j < str.Length; j++)
                {
                    if (str[j].IndexOf(Bind) != -1)
                    {
                        NewField += "," + str[j].Replace(Bind, TableList.Item(i).Attributes["Title"].Value);
                    }
                }
            }
            else if (SearchType.IndexOf("Empty") != -1)
            {
            }
            else
            {
                NewField += "," + TableList.Item(i).Attributes["Title"].Value + "=[" + Bind + "]";
            }
        }
        if (FWhere != "" && Where != "")
            Where = FWhere + Where;
        else if (FWhere != "" && Where == "")
            Where = FWhere.Remove(FWhere.Length - 5);
        Order = FOrder != "" ? FOrder.Remove(0, 1) : Order;
        //修改获取列
        dtlist = DBHelper.GetDataTable("select " + NewField.Replace("'", "''").Remove(0, 1) + " from " + Name + " " + (Where == "" ? "" : "where " + Where) + " " + (Order == "" ? "" : "Order by " + Order));

        StringBuilder OutFileContent = new StringBuilder();//容器
        //写头文件
        OutFileContent = AddHeadFile(OutFileContent);
        //写内容
        OutFileContent = AddContentFile(OutFileContent, dtlist);
        //写尾文件
        OutFileContent = AddEndFile(OutFileContent);
        return OutFileContent;
    }
    //Excel 头
    private StringBuilder AddHeadFile(StringBuilder OutFileContent)
    {

        OutFileContent.Append("<?xml version=\"1.0\"?>\r\n");

        OutFileContent.Append("<?mso-application progid=\"Excel.Sheet\"?>\r\n");

        OutFileContent.Append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");

        OutFileContent.Append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");

        OutFileContent.Append(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\n");

        OutFileContent.Append(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");

        OutFileContent.Append(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n");

        OutFileContent.Append(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n");

        OutFileContent.Append("  <Author>panss</Author>\r\n");

        OutFileContent.Append("  <LastAuthor>panss</LastAuthor>\r\n");

        OutFileContent.Append("  <Created>2004-12-31T03:40:31Z</Created>\r\n");

        OutFileContent.Append("  <Company>Prcedu</Company>\r\n");

        OutFileContent.Append("  <Version>12.00</Version>\r\n");

        OutFileContent.Append(" </DocumentProperties>\r\n");

        OutFileContent.Append(" <OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n");

        OutFileContent.Append("  <DownloadComponents/>\r\n");

        OutFileContent.Append("  <LocationOfComponents HRef=\"file:///F:\\Tools\\OfficeXP\\OfficeXP\\\"/>\r\n");

        OutFileContent.Append(" </OfficeDocumentSettings>\r\n");

        OutFileContent.Append(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n");

        OutFileContent.Append("  <WindowHeight>9000</WindowHeight>\r\n");

        OutFileContent.Append("  <WindowWidth>10620</WindowWidth>\r\n");

        OutFileContent.Append("  <WindowTopX>480</WindowTopX>\r\n");

        OutFileContent.Append("  <WindowTopY>15</WindowTopY>\r\n");

        OutFileContent.Append("  <ProtectStructure>False</ProtectStructure>\r\n");

        OutFileContent.Append("  <ProtectWindows>False</ProtectWindows>\r\n");

        OutFileContent.Append(" </ExcelWorkbook>\r\n");

        OutFileContent.Append(" <Styles>\r\n");

        OutFileContent.Append("  <Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n");

        OutFileContent.Append("   <Alignment ss:Vertical=\"Center\" />\r\n");

        OutFileContent.Append("   <Borders/>\r\n");

        OutFileContent.Append("   <Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"12\"/>\r\n");

        OutFileContent.Append("   <Interior/>\r\n");

        OutFileContent.Append("   <NumberFormat/>\r\n");

        OutFileContent.Append("   <Protection/>\r\n");

        OutFileContent.Append("  </Style>\r\n");

        OutFileContent.Append("  <Style ss:ID=\"s62\">\r\n");

        OutFileContent.Append("   <Alignment ss:Vertical=\"Center\" ss:Horizontal=\"Center\" ss:WrapText=\"1\"/>\r\n");

        OutFileContent.Append("   <Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"9\"/>\r\n");

        OutFileContent.Append("  </Style>\r\n");

        OutFileContent.Append("  <Style ss:ID=\"s74\">\r\n");

        OutFileContent.Append("   <Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\"/>\r\n");

        OutFileContent.Append("   <Borders>\r\n");

        OutFileContent.Append("  <Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>\r\n");

        OutFileContent.Append("  <Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>\r\n");

        OutFileContent.Append("  <Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>\r\n");

        OutFileContent.Append("  <Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>\r\n");

        OutFileContent.Append("  </Borders>\r\n");

        OutFileContent.Append("   <Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"12\" ss:Bold=\"1\"/>\r\n");

        OutFileContent.Append("   <Interior ss:Color=\"#BFBFBF\" ss:Pattern=\"Solid\"/>\r\n");

        OutFileContent.Append("  </Style>\r\n");

        OutFileContent.Append(" </Styles>\r\n");

        OutFileContent.Append(" <Worksheet ss:Name=\"Sheet1\">\r\n");

        OutFileContent.Append("  <Table ss:ExpandedColumnCount=\"255\" x:FullColumns=\"1\" \r\n");

        OutFileContent.Append("x:FullRows=\"1\" ss:StyleID=\"s62\" ss:DefaultColumnWidth=\"75\" ss:DefaultRowHeight=\"20.25\">\r\n");

        OutFileContent.Append("<Column ss:StyleID=\"s62\" ss:AutoFitWidth=\"0\" ss:Width=\"112.5\"/>\r\n");

        return OutFileContent;

    }
    //Excel 尾
    private StringBuilder AddEndFile(StringBuilder OutFileContent)
    {

        OutFileContent.Append("</Table>\r\n");

        OutFileContent.Append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n");

        OutFileContent.Append("<Unsynced/>\r\n");

        OutFileContent.Append("<Print>\r\n");

        OutFileContent.Append("    <ValidPrinterInfo/>\r\n");

        OutFileContent.Append("    <PaperSizeIndex>9</PaperSizeIndex>\r\n");

        OutFileContent.Append("    <HorizontalResolution>600</HorizontalResolution>\r\n");

        OutFileContent.Append("    <VerticalResolution>0</VerticalResolution>\r\n");

        OutFileContent.Append("</Print>\r\n");

        OutFileContent.Append("<Selected/>\r\n");

        OutFileContent.Append("<Panes>\r\n");

        OutFileContent.Append("    <Pane>\r\n");

        OutFileContent.Append("    <Number>3</Number>\r\n");

        OutFileContent.Append("    <RangeSelection>R1:R65536</RangeSelection>\r\n");

        OutFileContent.Append("    </Pane>\r\n");

        OutFileContent.Append("</Panes>\r\n");

        OutFileContent.Append("<ProtectObjects>False</ProtectObjects>\r\n");

        OutFileContent.Append("<ProtectScenarios>False</ProtectScenarios>\r\n");

        OutFileContent.Append("</WorksheetOptions>\r\n");

        OutFileContent.Append("</Worksheet>\r\n");

        OutFileContent.Append("<Worksheet ss:Name=\"Sheet2\">\r\n");

        OutFileContent.Append("<Table ss:ExpandedColumnCount=\"1\" ss:ExpandedRowCount=\"1\" x:FullColumns=\"1\"\r\n");

        OutFileContent.Append("x:FullRows=\"1\" ss:DefaultColumnWidth=\"54\" ss:DefaultRowHeight=\"14.25\">\r\n");

        OutFileContent.Append("<Row ss:AutoFitHeight=\"0\"/>\r\n");

        OutFileContent.Append("</Table>\r\n");

        OutFileContent.Append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n");

        OutFileContent.Append("<Unsynced/>\r\n");

        OutFileContent.Append("<ProtectObjects>False</ProtectObjects>\r\n");

        OutFileContent.Append("<ProtectScenarios>False</ProtectScenarios>\r\n");

        OutFileContent.Append("</WorksheetOptions>\r\n");

        OutFileContent.Append("</Worksheet>\r\n");

        OutFileContent.Append("<Worksheet ss:Name=\"Sheet3\">\r\n");

        OutFileContent.Append("<Table ss:ExpandedColumnCount=\"1\" ss:ExpandedRowCount=\"1\" x:FullColumns=\"1\"\r\n");

        OutFileContent.Append("x:FullRows=\"1\" ss:DefaultColumnWidth=\"54\" ss:DefaultRowHeight=\"14.25\">\r\n");

        OutFileContent.Append("<Row ss:AutoFitHeight=\"0\"/>\r\n");

        OutFileContent.Append("</Table>\r\n");

        OutFileContent.Append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n");

        OutFileContent.Append("<Unsynced/>\r\n");

        OutFileContent.Append("<ProtectObjects>False</ProtectObjects>\r\n");

        OutFileContent.Append("<ProtectScenarios>False</ProtectScenarios>\r\n");

        OutFileContent.Append("</WorksheetOptions>\r\n");

        OutFileContent.Append("</Worksheet>\r\n");

        OutFileContent.Append("</Workbook>\r\n");

        return OutFileContent;

    }
    //Excel 内容
    private StringBuilder AddContentFile(StringBuilder OutFileContent, DataTable dt)
    {
        //写列头
        OutFileContent.Append("<Row ss:AutoFitHeight=\"0\">");
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            OutFileContent.Append("<Cell><Data ss:Type=\"String\">" + dt.Columns[i].ColumnName + "</Data></Cell>");
        }
        OutFileContent.Append("</Row>");

        //写内容
        for (dti = 0; dti < dtlist.Rows.Count; dti++)
        {
            OutFileContent.Append("<Row ss:AutoFitHeight=\"0\">");
            for (int j = 0; j < TableList.Count; j++)
            {
                string Bind = TableList.Item(j).Attributes["Title"].Value;
                string BindType = TableList.Item(j).Attributes["BindType"] == null ? "" : TableList.Item(j).Attributes["BindType"].Value;
                string SearchType = TableList.Item(j).Attributes["SearchType"] == null ? "Equals" : TableList.Item(j).Attributes["SearchType"].Value;
                if (SearchType.IndexOf("Empty") != -1)
                { 

                }
                else if (BindType == "Time")
                {
                    OutFileContent.Append("<Cell><Data ss:Type=\"String\">" + (dtlist.Rows[dti][Bind] == null || dtlist.Rows[dti][Bind].ToString() == "" ? "" : Convert.ToDateTime(dtlist.Rows[dti][Bind]).ToString(TableList.Item(j).InnerText)) + "</Data></Cell>");
                }
                else if (BindType == "Html")
                {
                }
                else if (BindType == "Select")
                {
                    XmlNodeList xnl = TableList.Item(j).ChildNodes;
                    OutFileContent.Append("<Cell><Data ss:Type=\"String\">");
                    int f = 0;
                    for (int k = 0; k < xnl.Count; k++)
                    {
                        if (xnl.Item(k).Attributes["value"].Value == dtlist.Rows[dti][Bind].ToString())
                        {
                            OutFileContent.Append(NoHTML(reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind))));
                            f = 1;
                            break;
                        }
                        else if (xnl.Item(k).Attributes["session"] != null)
                        {
                            System.Web.UI.Page page = new System.Web.UI.Page();
                            if (page.Session[xnl.Item(k).Attributes["session"].Value].ToString() == dtlist.Rows[dti][Bind].ToString())
                            {
                                OutFileContent.Append(NoHTML(reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind))));
                                f = 1;
                                break;
                            }
                        }
                        else if (xnl.Item(k).Attributes["else"] != null)
                        {
                            OutFileContent.Append(NoHTML(reg.Replace(xnl.Item(k).InnerXml, new MatchEvaluator(GetBind))));
                            f = 1;
                            break;
                        }
                    }
                    if (f == 0)
                        OutFileContent.Append(dtlist.Rows[dti][Bind].ToString());
                    OutFileContent.Append("</Data></Cell>");
                }
                else
                {
                    OutFileContent.Append("<Cell><Data ss:Type=\"String\">" + dtlist.Rows[dti][Bind].ToString().Replace("<", "&lt;").Replace(">", "&gt;") + "</Data></Cell>");
                }
            }
            OutFileContent.Append("</Row>");
        }
        return OutFileContent;
    }
    //去除 html 标记
    public static string NoHTML(string Htmlstring)
    {
        //删除脚本
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
        return Htmlstring;

    }

}
